import * as THREE from 'three'
import createApp from '../../core'

function createCylinderGeometry (dom: HTMLElement) {
  const { camera, scene, update, gui } = createApp(dom)

  camera.position.set(0, 0, 100)
  camera.lookAt(scene.position)

  const mesh = createCylinderFromGeometry()
  mesh.position.set(-30, 0, 0)
  scene.add(mesh)

  const bufferMesh = createCylinderFromBufferGeometry()
  bufferMesh.position.set(30, 0, 0)
  scene.add(bufferMesh)

  update((time: number) => {
    const angle = time / 2000
    mesh.rotation.set(angle, angle, 0)
    bufferMesh.rotation.set(angle, angle, 0)
  })

  function updateMeshs () {
    generateGeometry(mesh)
    generateGeometry(bufferMesh)
  }

  gui.add(data, 'radiusTop', 0, 30).onChange(updateMeshs)
  gui.add(data, 'radiusBottom', 0, 30).onChange(updateMeshs)
  gui.add(data, 'height', 0, 30).onChange(updateMeshs)
  gui.add(data, 'radialSegments', 1, 30, 1).onChange(updateMeshs)
  gui.add(data, 'heightSegments', 1, 30, 1).onChange(updateMeshs)
  gui.add(data, 'openEnded').onChange(updateMeshs)
  gui.add(data, 'thetaStart', 0, Math.PI * 2).onChange(updateMeshs)
  gui.add(data, 'thetaLength', 0, Math.PI * 2).onChange(updateMeshs)
}

const data = {
  radiusTop: 10,
  radiusBottom: 20,
  height: 20,
  radialSegments: 10,
  heightSegments: 10,
  openEnded: false,
  thetaStart: 0,
  thetaLength: Math.PI * 2
}

function createCylinderFromGeometry () {
  const { radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength } = data
  const geometry = new THREE.CylinderGeometry(radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength)
  const material = new THREE.MeshBasicMaterial({ color: 0xffff00, wireframe: true })
  const mesh = new THREE.Mesh(geometry, material)
  return mesh
}

function createCylinderFromBufferGeometry () {
  const { radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength } = data
  const geometry = new THREE.CylinderBufferGeometry(radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength)
  const material = new THREE.MeshNormalMaterial({ side: THREE.DoubleSide })
  const mesh = new THREE.Mesh(geometry, material)
  return mesh
}

function generateGeometry (mesh: THREE.Mesh) {
  const { radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength } = data
  const geometry = new THREE.CylinderBufferGeometry(radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength)
  mesh.geometry.dispose()
  mesh.geometry = geometry
}

export {
  createCylinderGeometry
}
